package com.koujun.meinv.server.caipiao;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

import com.koujun.meinv.server.StringUtils;

public class AiCaiParser {
	private static String baseurl = "http://www.310win.com/blog/{id}/current.html";
	private static String detailurl = "http://www.310win.com";
	public static List<Item> formParam = new ArrayList<Item>();

	public static void main(String[] args) throws IOException, Exception {
		AiCaiParser api = new AiCaiParser();
		List<String> orders = api.getOrders("314548");
		for (String s : orders) {
			System.out.println(s);
		}
	}

	public List<String> getOrders(String id) throws IOException, Exception {
		String httpURL = baseurl.replace("{id}", id);
		return parseOrder(post(httpURL, 1));
	}

	public List<String> parseOrder(String html) throws Exception {
		int start = html.indexOf("<div class=\"us_div1\">");
		int end = html.indexOf("</table>", start);
		html = html.substring(start, end);
		List<String> map = new ArrayList<String>();
		String[] split = html.split("<a href=\"");
		for (int i = 1; i < split.length; i++) {
			int herfIndex = split[i].indexOf("/Info/scheme");
			if (herfIndex == -1) {
				continue;
			}
			if (split[i].indexOf("双色球") > -1) {
				continue;
			}
			if (split[i].indexOf("已返奖") > -1) {
				continue;
			}
			int endx = split[i].indexOf("'", herfIndex);
			String ds = detailurl + split[i].substring(herfIndex, endx);
			map.add(ds);
		}
		return map;
	}

	public String getDetail(String url) throws Exception {
		String res = StringUtils.requestURLAsString(url);
		int start = res.indexOf("id=\"matchTables\"");
		int end = res.indexOf("</table>", start);
		res = res.substring(start, end).replace("id=\"matchTables\">", "")
				+ "</table>";
		return res.trim();
	}

	public String post(String httpURL, int page) throws IOException {
		HttpClient client = new HttpClient();
		if (page == 1) {
			String response = StringUtils.requestURLAsString(httpURL);
			formParam = Item.getFormParam(response);
			return response;
		}
		PostMethod post = new PostMethod(httpURL);
		post.setRequestHeader("Content-Type",
				"application/x-www-form-urlencoded");
		formParam.add(new Item("__EVENTARGUMENT", String.valueOf(page)));
		formParam.add(new Item("__EVENTTARGET", "ctl05$AspNetPager2"));
		for (Item i : formParam) {
			post.addParameter(i.name, i.value);
		}
		client.executeMethod(post);
		String res = post.getResponseBodyAsString();
		formParam = Item.getFormParam(res);
		return post.getResponseBodyAsString();
	}

}
